package com.shaw.study.springx.webmvc;

import com.sun.corba.se.impl.encoding.OSFCodeSetRegistry;
import com.sun.org.apache.xerces.internal.impl.xpath.regex.Match;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by asus on 2018/5/1.
 */
public class ViewResolver {
    private String viewName;
    private File viewFile;

    public ViewResolver(String viewName, File viewFile) {
        this.viewName = viewName;
        this.viewFile = viewFile;
    }

    public String getViewName() {
        return viewName;
    }

    /**
     * 进行view中的值转化
     * @param modelAndView
     * @return
     */
    public String viewResolver(ModelAndView modelAndView){
        StringBuilder sb = new StringBuilder();
        try {
            RandomAccessFile file = new RandomAccessFile(viewFile,"r");

            String line = "";
            while(null!=(line=file.readLine())){
//                Matcher m = matcher(line);
//                while (m.find()) {
//                    for (int i = 1; i <= m.groupCount(); i++) {
//
//                        //要把${}中间的这个字符串给取出来
//                        String paramName = m.group(i);
//                        Object paramValue = modelAndView.getModel().get(paramName);
//                        if (null == paramValue) {
//                            continue;
//                        }
//                        line = line.replaceAll(m.pattern().toString(), paramValue.toString());
//                        line = new String(line.getBytes("utf-8"), "ISO-8859-1");
//                    }
//                }
                Map<String, Object>  modelMap = (Map<String, Object>) modelAndView.getModel();
                for(Map.Entry<String,Object> entry: modelMap.entrySet()){
                    line = line.replaceAll(getPatter(entry.getKey()), entry.getValue().toString());
                }
                sb.append(line);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    private static String getPatter(String s){
        StringBuilder sb = new StringBuilder();
        sb.append(escapeExprSpecialWord("$"));
        sb.append(escapeExprSpecialWord("{"));
        sb.append(s);
        sb.append(escapeExprSpecialWord("}"));

        return sb.toString();
    }

    public static Matcher matcher(String line){
        StringBuilder sb = new StringBuilder();
        sb.append(".");
        sb.append("*");
        sb.append(escapeExprSpecialWord("$"));
        sb.append(escapeExprSpecialWord("{"));
        sb.append(".");
        sb.append("+");
        sb.append("?");
        sb.append(escapeExprSpecialWord("}"));
        sb.append(".");
        sb.append("*");

        Pattern pattern = Pattern.compile(sb.toString(),Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(line);
        return matcher;
    }

    public static void main(String[] args) {
        String s = "adfa${username}sdfsdf${username}";
        Matcher matcher = matcher(s);
        int i = 0;
        while(matcher.find()) {
//            for (int i = 0; i < matcher.groupCount(); i++) {
//                System.out.println(matcher.group(i));
//            }
            System.out.println(matcher.groupCount());
        }

        s = s.replaceAll(getPatter("username"),"111");
        System.out.println(s);
    }

    /**
     * 转义正则特殊字符 （$()*+.[]?\^{},|）
     *
     * @param keyword
     * @return
     */
    public static String escapeExprSpecialWord(String keyword) {
        if (StringUtils.isNotBlank(keyword)) {
            String[] fbsArr = { "\\", "$", "(", ")", "*", "+", ".", "[", "]", "?", "^", "{", "}", "|" };
            for (String key : fbsArr) {
                if (keyword.contains(key)) {
                    keyword = keyword.replace(key, "\\" + key);
                }
            }
        }
        return keyword;
    }
}
